﻿@using DCMS.Web.Framework.UI;
@using DCMS.Web.Framework;
@using DCMS.Core.Domain.Common;
@using DCMS.ViewModel.Models.Sales;
@using DCMS.Services.Sales;
@using DCMS.Core.Infrastructure;

@model ReturnReservationBillModel


<script type="text/javascript">

    jQuery(document).ready(function () {
        "use strict";
        // Init Theme Core
        Core.init({
            sbm: "sb-l-c",
        });
        // Init Demo JS
        Demo.init();

        var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
        if (model.ReversedStatus) {
            $("#inkpadBox").hide();
            $("#inkpadBox1").css('display', 'block');
        }
        if (model.AllowSelectionDateRange > 0) {
            var maxDate = $(this).dateFtt("yyyy-MM-dd", new Date());
            var minDate = new Date(maxDate).setDate(new Date(maxDate).getDate() - model.AllowSelectionDateRange);
            minDate = $(this).dateFtt("yyyy-MM-dd", new Date(minDate));

            $('#datetimepicker_TransactionDate').data("DateTimePicker").maxDate(maxDate);
            $('#datetimepicker_TransactionDate').data("DateTimePicker").minDate(minDate);
        }

        /*
         * ======================================================
         * mschen 2018-12-5 11:24:43 begin
         * ======================================================
         */

        //审核
		$("#btn_auditing").click(function () {
	         //防止重复保存
	         var loadingButton = Ladda.create(this);
            loadingButton.start();
            var returnUrl = "@Context.Request.Query["returnURL"]";
            if (returnUrl.indexOf("AuditedStatus=") == -1) {
                if (returnUrl.indexOf("?") == -1) {
                    returnUrl += "?";
                } else {
                    returnUrl += "&";
                }
                returnUrl += "AuditedStatus=False";
            } else {
                if (returnUrl.indexOf("AuditedStatus=False") == -1) {
                    returnUrl = returnUrl.replace("AuditedStatus=", "AuditedStatus=False");
                }
            }
            returnUrl = returnUrl.replace(/amp;/g, "");
            $(this).remoteSubmit("get", "/ReturnReservationBill/Auditing", { id: "@Model.Id" }, null, function () { location.href = returnUrl; },null,loadingButton);
		});

        //红冲
		$("#btn_red").click(function () {
	        //防止重复保存
	        var loadingButton = Ladda.create(this);

            WinMsg.confirm({ message: "确认要红冲吗？" }).on(function (e) {
				if (!e) {
					return;
				}
	            loadingButton.start();
				$(this).remoteSubmit("get", "/ReturnReservationBill/Reverse", { id: "@Model.Id" }, null, function () { location.href = "/ReturnReservationBill/List"; },null,loadingButton);
			});
        });

        //作废
        $("#btn_cancel").click(function () {
			//防止重复保存
			var loadingButton = Ladda.create(this);

			WinMsg.confirm({ message: "确认要作废吗？" }).on(function (e) {
				if (!e) {
					return;
				}
				loadingButton.start();
                $(this).remoteSubmit("get", "/ReturnReservationBill/Delete", { id: "@Model.Id" }, null, function () { location.href = "/ReturnReservationBill/List"; }, null, loadingButton);
			});
		});

		//打印
		$("#btn_print").click(function () {
	        //防止重复保存
	        var loadingButton = Ladda.create(this);
            WinMsg.confirm({ message: "确认要打印吗？" }).on(function (e) {
				if (!e) {
					return;
				}
                loadingButton.start();
                var setting = {}
                var LODOP = null;
                var rs = $(this).getSyncData("/ReturnReservationBill/PrintSetting", null, "get");
                if (rs.Success) {
                    setting = rs.Data;
                    loadCLodop(document, setting.PrintPort, function () {
                        //判断页面是否已加载LODOP
                        if (LODOP == null || LODOP == undefined) {
                            LODOP = getLodopFirst(document);
                            LODOP = getLodopSecond(document);
                        }
                        if (LODOP == null || LODOP == undefined) {
                            loadingButton.stop();
                            return;
                        } else {
                            $("#printData").html("");
                        }
                        $(this).remoteSubmit("get", "/ReturnReservationBill/Print", { selectData: "@Model.Id" }, null, function (result) {
                            if (result.Success) {
                                var html = result.Data;
                                LODOP.PRINT_INIT("退货订单");
                                if (!isNaN(setting.PaperWidth) && !isNaN(setting.PaperHeight)) {
                                    LODOP.SET_PRINT_PAGESIZE(1, setting.PaperWidth + "mm", setting.PaperHeight + "mm");
                                }
                                if (setting.IsPrintPageNumber) {
                                    LODOP.ADD_PRINT_HTM(1, 600, 300, 100, "总页号：<font color='#0000ff' format='ChineseNum'><span tdata='pageNO'>第##页</span>/<span tdata='pageCount'>共##页</span></font>");
                                }
                                if (!isNaN(setting.MarginTop) && !isNaN(setting.MarginLeft) && !isNaN(setting.MarginRight) && !isNaN(setting.MarginBottom)) {
                                    LODOP.ADD_PRINT_HTM(setting.MarginTop + "mm", setting.MarginLeft + "mm", "RightMargin:" + setting.MarginRight + "mm", "BottomMargin:" + setting.MarginBottom + "mm", html);
                                }
                                LODOP.SET_PRINT_STYLEA(0, "Horient", 2);
                                LODOP.PREVIEW(true);
                                toastr.success(result.Message);
                                loadingButton.stop();
                            }
                            else {
                                $(this).showToastr(result.Message);
                            }
                        }, null, loadingButton);
                    });
                }
			});
        });

		//客户搜索
		$(document).on('click', "#btn_search_customer", function () {
			var actionUrl = "/Terminal/AsyncSearchSelectPopup";
			$(this).showModalV2($("#TerminalSelectModalWindow"), actionUrl, { ids: "" }, "选择终端", $("#TerminalSelectForm"), function (rows) { });
		});

        //选择终端绑定事件
        window.operateEventsPopTerminal = {
            'click .rowSelect': function (e, value, row, index) {
                try {
                    var businessUserId = $("#BusinessUserId").val();

                    //检查是否需要提供赠品
                    $(this).remoteRequest('GET', '/Terminal/CheckTerminalHasGives', {
                        terminalId: row.Id,
                        businessUserId: businessUserId
                    },
                        function (data) {
                            if (data.HasGives) {
                                $("#GiveQuotaSelectBox").show();
                            }
                            else {
                                $("#GiveQuotaSelectBox").hide();
                            }
                        });

                    $("#ChannelId").val(row.ChannelId);
                    $("#TerminalId").val(row.Id);
                    $("#TerminalName").val(row.Name);
                    $('#TerminalSelectModalWindow').modal('hide');

                    if (row.Id > 0) {
                        $(".TBalance_Box").show();
                    }
                    else {
                        $(".TBalance_Box").hide();
                    }

                    //终端最大欠款
                    $("#TerminalMaxAmount").val(parseFloat(row.MaxAmountOwed).toFixed(2));
                    $(this).remoteRequest('GET', '/Terminal/GetTerminalBalance', { terminalId: row.Id }, function (data) {
                        $("#TBalance_MaxOweCashBalance").val(parseFloat(data.MaxOweCashBalance).toFixed(2));
                        $("#TBalance_AdvanceAmountBalance").val(parseFloat(data.AdvanceAmountBalance).toFixed(2));
                        $("#TBalance_TotalOweCash").val(parseFloat(data.TotalOweCash).toFixed(2));
                    });
                }
                catch (err) {
                    console.log(err);
                    $(this).showToastr(err);
                    return;
                }
            }
        };


		 //选择业务员，获取业务员额度
        $("#BusinessUserId").change(function ()
        {
            var businessUserId = $("#BusinessUserId").val();
            if (businessUserId != null) {
                $(".UBalance_Box").show();
            }
            else {
                $(".UBalance_Box").hide();
            }
            if (businessUserId != null && businessUserId != "" && businessUserId != 0) {
                $(document).remoteRequest('GET', '/RecordingVoucher/GetUserOwnCash', { userId: businessUserId }, function (data) {
                    //业务员已用欠款
                    $("#UserUsedAmount").val(parseFloat(data.UserUsedAmount).toFixed(2));
                    //业务员可用欠款
                    $("#UserAvailableAmount").val(parseFloat(data.UserAvailableOweCash).toFixed(2));
                });
            }
        });


        //商品列表选择赋值
        window.operateEventsPop = {
			'click .rowSelect': function (e, value, row, index) {
                productOperateEvents(row, $(this).attr("data-id"), this);
			}
        };
        var productOperateEvents = function (row, index, _this) {
            try {
                var wareHouseId = $("#WareHouseId").val();
                var terminalId = $("#TerminalId").val();

                var keys = Object.keys(row.Units);
                var isMinUnitSale = $("#IsMinUnitSale").val();
                var dateKeys = Object.keys(row.ProductTimes);

                //1.初始商品单位
                //初始最小单位单位
                var unitId = row.SmallUnitId;
                var unitName = keys[0];
                //如果不是最小单位
                if (isMinUnitSale != "1" && isMinUnitSale != "True") {
                    //有大单位赋值大单位
                    if (row.BigUnitId != null && row.BigUnitId != 0) {
                        unitId = row.BigUnitId;
                        unitName = keys[2];
                    } else {
                        //有中单位赋值中单位
                        if (row.StrokeUnitId != null && row.StrokeUnitId != 0) {
                            unitId = row.StrokeUnitId;
                            unitName = keys[1];
                        }
                    }
                }

                //成本价
                var costPrice = 0;
                var ck = Object.keys(row.CostPrices);
                var cv = Object.values(row.CostPrices);
                ck.forEach(function (a, b) {
                    if (a == unitId) {
                        costPrice = cv[b];
                    }
                });

                //2.初始商品价格、参考价格
                var referPrices; //参照价格
                var defaultAmountId = $("#DefaultAmountId").val();
                //默认价格
                var prices;

                //如果此商品有价格体系
                row.ProductTierPrices.forEach(function (a, b) {
                    var planIdTypeId = a.PricesPlanId + "_" + a.PriceTypeId;
                    if (defaultAmountId == planIdTypeId) {
                        if (unitId == row.SmallUnitId) {
                            prices = a.SmallUnitPrice;
                            if (model.VariablePriceCommodity == 0) {
                                referPrices = a.SmallUnitPrice;
                            }
                        }
                        else if (unitId == row.StrokeUnitId) {
                            prices = a.StrokeUnitPrice;
                            if (model.VariablePriceCommodity == 0) {
                                referPrices = a.StrokeUnitPrice;
                            }
                        }
                        else if (unitId == row.BigUnitId) {
                            prices = a.BigUnitPrice;
                            if (model.VariablePriceCommodity == 0) {
                                referPrices = a.BigUnitPrice;
                            }
                        }
                    }
                });

                //3.参考批发价格
                if (model.VariablePriceCommodity !== 0) {
                    if (unitId == row.SmallUnitId) {
                        referPrices = row.Prices[0].ProductPrice.TradePrice;
                    }
                    else if (unitId == row.StrokeUnitId) {
                        referPrices = row.Prices[1].ProductPrice.TradePrice;
                    }
                    else if (unitId == row.BigUnitId) {
                        referPrices = row.Prices[2].ProductPrice.TradePrice;
                    }
                }

                //4.库存数量
                var stockQty = 0;
                //仓库Id
                var wareHouseId = $("#WareHouseId").val();
                row.StockQuantities.forEach(function (a, b) {
                    if (a.WareHouseId == wareHouseId) {
                        stockQty = a.UsableQuantity;
                    }
                });

                $("#ReturnReservationItems").bootstrapTable('updateRow', {
                    index: index, row: {
                        ProductSKU: row.Sku,
                        ProductId: row.Id,
                        ProductName: row.Name,
                        BarCode: row.SmallBarCode,
                        UnitConversion: row.UnitConversion,
                        ProductTimes: row.ProductTimes,
                        IsManufactureDete: row.IsManufactureDete,
                        ManufactureDete: dateKeys[0],
                        Units: row.Units,
                        UnitId: unitId,
                        UnitName: unitName,
                        Price: prices,
                        Quantity: 0,
                        Amount: 0,
                        CostPrices: row.CostPrices,
                        CostPrice: costPrice,
                        CostAmount: 0,
                        Prices: row.Prices,
                        ProductTierPrices: row.ProductTierPrices,  //价格体系
                        StockQty: stockQty,
                        StockQuantities: row.StockQuantities, //库存数量
                        BigQuantity: row.BigQuantity,//大转小
                        StrokeQuantity: row.StrokeQuantity,//中转小
                        SmallUnitId: row.SmallUnitId,  //小单位
                        StrokeUnitId: row.StrokeUnitId,  //中单位
                        BigUnitId: row.BigUnitId,  //大单位
                        IsAdjustPrice: row.IsAdjustPrice, //是否允许改价
                        ReferPrices: referPrices, //参照价格
                        Profit: 0, //利润
                        CostProfitRate: 0, //成本利润率
                        TaxRate: "@Model.TaxRate", //税率%
                        ContainTaxPrice: 0, //含税价格
                        TaxPrice: 0, //税额
                        TaxPriceAmount: 0 //税价总计
                    }
                });
                //$("#ReturnReservationItems").bootstrapTable('refresh');
                $('#ModalProductWindows').modal('hide');

            }
            catch (err) {
                console.log(err);
                $(_this).showToastr(err);
                return;
            }
        };

        //计算已收金额
        function SumAlreadyAmount() {
            var sumAlreadyAmount = 0;
            var colls = $("input[name='CollectionAmount']");
			for (var i = 0; i < colls.length; i++) {

				if (isNaN($(colls[i]).val()) || $(colls[i]).val() == "") {
					$(colls[i]).val("0.00")
				}

				sumAlreadyAmount = parseFloat(sumAlreadyAmount) + parseFloat(colls[i].value);
            }
            return sumAlreadyAmount;
        }

		//表单检查
		var formValidator = function () {
            var isVaild = true;

            if ($("#TerminalId").val() == "" || $("#TerminalId").val() == "0") {
                $("#TerminalId").focus();
                $(this).showToastr("请先选择客户！");
                return false;
            }
            else if ($("#BusinessUserId").val() == "") {
                $("#BusinessUserId").focus();
                $(this).showToastr("请先选择业务员！");
                return false;
            }
            else if ($("#WareHouseId").val() == "") {
                $("#WareHouseId").focus();
                $(this).showToastr("请先选择仓库！");
                return false;
            }
            else if ($("#DeliveryUserId").val() == "") {
                $("#DeliveryUserId").focus();
                $(this).showToastr("请先选择送货员！");
                return false;
            }
            else if ($("#PayTypeId").val() == "0") {
                $("#PayTypeId").focus();
                $(this).showToastr("请先选择付款方式！");
                return false;
            }
            else if ($("input[name='TransactionDate']").val() == "") {
                $("input[name='TransactionDate']").focus();
                $(this).showToastr("请先选择交易日期！");
                return false;
            }
            else if ($("#IsMinUnitSale").val() == "") {
                $("#IsMinUnitSale").focus();
                $(this).showToastr("请先选择按最小单位销售！");
                return false;
            }
            else if ($("#DefaultAmountId").val() == "") {
                $("#DefaultAmountId").focus();
                $(this).showToastr("请先选择价格体系！");
                return false;
			}
			else if (parseFloat($("#PreferentialEndAmount").val()) < SumAlreadyAmount()) {
				//$("#IsMinUnitPurchase").focus();
				$("input[name='CollectionAmount']")[0].focus();
				$(this).showToastr("当前付款总金额不能大于优惠后金额！");
				isVaild = false;
			}

			return isVaild;
		}

        //退货订单项目
        $("#ReturnReservationItems").bootstrapTable({
               @Html.Raw(Model.Items.Count > 0 ? "url: '/ReturnReservationBill/AsyncReturnReservationItems?returnReservationBillId=" + Model.Id+"'," : "length: 9,")
            striped: true,
            cache: false,
            pagination: true,
            showPagination: false,
            sidePagination: "server",
            sortable: false,
            sortOrder: "asc",
            search: false,
            strictSearch: false,
            showColumns: false,
            showRefresh: false,
            clickToSelect: false,
            uniqueId: "id",
            showToggle: false,
            editable: true,
            cardView: false,
            detailView: false,
            showFooter: true,
            onLoadSuccess: function (data) {
                $(".fixed-table-pagination").hide();
                if (data.hidden == true) {
                    $('#ReturnReservationItems').bootstrapTable('showColumn', 'TaxRate');
                    $('#ReturnReservationItems').bootstrapTable('showColumn', 'ContainTaxPrice');
                    $('#ReturnReservationItems').bootstrapTable('showColumn', 'TaxPrice');
                    $('#ReturnReservationItems').bootstrapTable('showColumn', 'TaxPriceAmount');
                }
            },
            onPostBody: function (data) {
                $("[data-toggle='popover']").popover();
            },
            columns: [
                {
                    title: '<i class="fa fa-gear fs18"></i>',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return m_pagerow + index + 1;
                    },
                    footerFormatter: function (value) {
                        return '总计';
                    }
                },
                {
                    field: 'ProductCode',
                    title: '商品编号',
                    align: 'center', visible: false
                },
                { field: 'UnitId', visible: false },
                { field: 'Units', visible: false },
                { field: 'Prices', visible: false },
                { field: 'ProductTierPrices', visible: false },  //价格体系
                { field: 'SmallUnitId', visible: false }, //小单位
                { field: 'StrokeUnitId', visible: false }, //中单位
                { field: 'BigUnitId', visible: false }, //大单位

                { field: 'ProductId', visible: false },
                { field: 'IsAdjustPrice', visible: false },
                { field: 'ReferPrices', visible: false }, //参照价格
                {
                    field: 'ProductName',
                    title: '商品名称',
                    align: 'center',
                    width:300,
                    formatter: function (value) {
                        return (value == 0 || value == "" || value == undefined) ? "" : @Model.Id== 0 ? $(this).cutString(value, 50) : "<a style='color:black; text-decoration:none;'  data-trigger='hover' title='' data-container='body' data-toggle='popover' data-placement='top' data-content='" + value + "'>" + $(this).cutString(value, 50) + "</a>";
                    }
                },
                {
                    field: 'SmallBarCode',
                    title: '条形码',
                    align: 'center' ,
                    formatter: $(this).formatIsNull
                },
                {
                    field: 'UnitName',
                    title: '单位',
                    align: 'center',
                    formatter: $(this).formatIsNull
                },
                {
                    field: 'UnitConversion',
                    title: '单位换算',
                    align: 'center',
                    formatter: $(this).formatIsNull
                },
                {
					field: 'Quantity',
					align: 'center',
					width: '100',
					title: '数量',
                    formatter: function (value, row, index) {
                        if (Object.keys(row).length > 1) {
                            return (value == 0 || value == "") ? "" : value + "" + row.UnitName;
                        }
                        else {
                            return "";
                        }
                    },
                    align: 'center'
                },
                { field: 'IsManufactureDete', visible: false },  //该商品是否开启生产日期功能
                { field: 'ProductTimes', visible: false },
                {
                    field: 'ManufactureDete',
                    title: '生产日期',
                    visible: model.IsShowCreateDate,
                    align: 'center'
                    , visible: false
                },
                {
                    field: 'Price',
                    title: '价格', width: '100',
                    formatter: function (value, row, index) {

                        if (Object.keys(row).length > 1)
                        {
                            value = $(this).formatFixed(value);

                            if (row.ReferPrices && row.ReferPrices != "" && row.ReferPrices != null) {
                                if (value != "" && value != row.ReferPrices) {
                                    return "<span alt=" + value + " style='color:#f34a70;'>" + value + "</span>";
                                }
                                else {
                                    return value;
                                }
                            }
                            else {
                                if (value != "" && value != row.Prices[0].ProductPrice.TradePrice) {
                                    return "<span alt=" + value + " style='color:#f34a70;'>" + value + "</span>";
                                }
                                else {
                                    return value;
                                }
                            }
                        }
                        else {
                            return (value == 0 || value == "" || value == undefined) ? "" : value
                        }
                    },
                    align: 'center'
                },


                { field: 'CostPrices', visible: false },
                {
                    field: 'CostPrice',
                    title: '成本价', visible: false, align: 'right', formatter: $(this).formatFixed
                },
                {
                    field: 'CostAmount',
                    title: '成本金额', visible: false, align: 'right', formatter: $(this).formatFixed
                },
                { field: 'Profit', title: '利润', align: 'right', align: 'right', formatter: $(this).formatFixed},
                { field: 'CostProfitRate', title: '成本利润率%', align: 'right', formatter: $(this).formatFixed},
                { field: 'TaxRate', title: '税率%', align: 'right', visible: '@Model.EnableTaxRate' == 'True', formatter: $(this).formatFixed},
				{ field: 'ContainTaxPrice', title: '含税价格',align: 'right', visible: '@Model.EnableTaxRate' == 'True',formatter: $(this).formatFixed },
				{ field: 'TaxPrice', title: '税额',align: 'right', visible: '@Model.EnableTaxRate' == 'True',formatter: $(this).formatFixed },
                {
                    field: 'TaxPriceAmount', title: '税价总计', align: 'right', visible: '@Model.EnableTaxRate' == 'True', formatter: $(this).formatFixed
                },
                   {
                    field: 'Amount',
                    title: '金额',
                    width: '100',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return (value == 0 || value == "" ||value == undefined) ? "" : parseFloat(value).toFixed(2);
                    },
                    footerFormatter: function (value) {
                        var count = $(this).alculateTaxAmountSub('@Model.Id', '@Model.AuditedStatus', '#ReturnReservationItems', '@Model.EnableTaxRate', value);

                        var total = parseFloat((typeof (count) == 'undefined' || count == "") ? '0' : count);

                        var otherAmount = 0;
                        var accounts = $("#ReturnReservationItems_Partial_Form").find("input[name='CollectionAmount']");
                        $.each(accounts, function (i, input) {
                            var option = $(input).attr("data-account");
                            var amount = $(input).val();
                            if ($("#CollectionAccount").val() !== option) {
                                otherAmount += amount;
                            }
                        });

                        $("#SumAmount").val(total);

                        //单据审核后 欠款金额=当前实际欠款金额
                        if ("@Model.Id" != "0" && "@Model.AuditedStatus" == "True")
                        {
                            $("#PreferentialAmount").val(parseFloat("@Model.PreferentialAmount")); //优惠金额
                            $("#PreferentialEndAmount").val(parseFloat("@Model.PreferentialEndAmount")); //优惠后金额
                            $("#OweCash").val(parseFloat("@Model.OweCash")); //欠款金额
						}
                        else {

                            $("#CollectionAmount").val(parseFloat(total - otherAmount).toFixed(2));

                            //优惠金额
                            $("#PreferentialAmount").val(parseFloat($("#PreferentialAmount").val()).toFixed(2));
                            //优惠后金额=总金额 - 优惠金额
                            $("#PreferentialEndAmount").val(parseFloat(total - parseFloat($("#PreferentialAmount").val())).toFixed(2));

                            //欠款金额=优惠后金额 - 已收金额
                            $("#OweCash").val(parseFloat(parseFloat($("#PreferentialEndAmount").val()) - SumAlreadyAmount()).toFixed(2));
						}

                        return total.toFixed(2);
                    }
				},
                {
					field: 'StockQty',
					title: '库存数量',
					align: 'center',
					width: '100',
					formatter: function (value, row, index) {

						if (value != "" && row.ProductId != "" && row.ProductId > 0) {

							var bigUnitId = row.BigUnitId;
							var bigUnitName = "";

							var strokeUnitId = row.StrokeUnitId;
							var strokeUnitName = "";

							var smallUnitId = row.SmallUnitId;
							var smallUnitName = "";

							$.each(row.Units, function (key, unit) {
								if (unit == bigUnitId) {
									bigUnitName = key;
								}
								else if (unit == strokeUnitId) {
									strokeUnitName = key;
								}
								else if (unit == smallUnitId) {
									smallUnitName = key;
								}
							});

							//计算结果数量
							var resultQuantity = value;
							//大单位计算结果
							var big = parseInt(resultQuantity / row.BigQuantity);
							resultQuantity = resultQuantity - big * row.BigQuantity;
							//中单位计算结果
							var stroke = 0;
							if (strokeUnitId > 0 && row.StrokeQuantity > 0) {
								stroke = parseInt(resultQuantity / row.StrokeQuantity);
								resultQuantity = resultQuantity - stroke * row.StrokeQuantity;
							}
							//小单位计算结果
							var small = resultQuantity;

                            var content = big + "" + bigUnitName;

                            if (stroke > 0)
                                content += ((strokeUnitId > 0) ? (stroke + "" + strokeUnitName) : "");

							 if (small > 0)
                                content += small + "" + smallUnitName

							return "<span alt=" + value + ">" + content + "</span>";

						}
						else {
							return "";
						}
					}
                },
                {
                    field: 'Remark',
                    title: '备注',
                    align: 'center',
                    formatter: $(this).formatIsNull
                },
                //{
                //    field: 'OrderCode',
                //    title: '订货单编号',
                //    align: 'center'
                //},
                //{
                //    field: 'RemainderQty',
                //    title: '剩余还货数量',
                //    align: 'center'
                //},
                {
                    field: 'Operate',
                    title: '操作',
                    align: 'center',
                    width: '130',
                    events: {
						'click .rowAppend': function (e, value, row, index) {// 添加
							//审核、红冲后不能修改
							if ("@Model.AuditedStatus" == "True" || "@Model.ReversedStatus" == "True") {
								return false;
							}
                            $('#ReturnReservationItems').bootstrapTable('insert', row);
                            //修改最后一条数据uniqueid,防止复制时uniqueid相同，删除时都删除
                            var allTableData = $('#SaleItems').bootstrapTable('getData');
                            var maxuniqueid = 0;
                            $.each(allTableData, function (i, row) {
                                if (row.uniqueid > maxuniqueid) {
                                    maxuniqueid = row.uniqueid;
                                }
                            });
                            allTableData[allTableData.length - 1].uniqueid = maxuniqueid + 1;
                            allTableData[allTableData.length - 1].Id = 0;
                        },
						'click .rowCopy': function (e, value, row, index) {// 复制
							//审核、红冲后不能修改
							if ("@Model.AuditedStatus" == "True" || "@Model.ReversedStatus" == "True") {
								return false;
							}
							$('#ReturnReservationItems').bootstrapTable('copying', row);
                            //修改最后一条数据uniqueid,防止复制时uniqueid相同，删除时都删除
							var allTableData = $('#ReturnReservationItems').bootstrapTable('getData');
							var maxuniqueid = 0;
							$.each(allTableData, function (i, row) {
								if (row.uniqueid > maxuniqueid) {
									maxuniqueid = row.uniqueid;
								}
							});
                            allTableData[allTableData.length - 1].uniqueid = maxuniqueid + 1;
                            allTableData[allTableData.length - 1].Id = 0;
                            allTableData[allTableData.length - 1].IsGifts = false;
                        },
						'click .rowDel': function (e, value, row, index) {// 删除
							//审核、红冲后不能修改
                            if ("@Model.AuditedStatus" == "True" || "@Model.ReversedStatus" == "True") {
                                $(this).showToastr('审核、红冲后不能修改');
								return false;
							}
							//$("#ReturnReservationItems").bootstrapTable('remove', { field: "uniqueid", values: [parseInt(row.uniqueid)] });
							var datas = $('#ReturnReservationItems').bootstrapTable('getData');
							var len = datas.length;
							if (len == 1) {
                                $(this).showToastr('单据项目不能留空');
								return;
							}

							if (row.uniqueid == undefined) {
								$("#ReturnReservationItems").bootstrapTable('remove', { field: "Id", values: [parseInt(row.Id)] });
							}
							else {
								$("#ReturnReservationItems").bootstrapTable('remove', { field: "uniqueid", values: [parseInt(row.uniqueid)] });
							}
                        }
                    },
                    formatter: function (value, row, index) {
                        return [
                            '<button type="button" class="btn btn-sm btn-default rowAppend" title="添加"><i class="fa fa-plus" ></i></button>',
                            '<button type="button" class="btn btn-sm btn-default rowCopy" title="复制"><i class="fa fa-copy" ></i></button>',
                            '<button type="button" class="btn btn-sm btn-default rowDel" title="删除"><i class="fa fa-trash-o"></i></button>'
                        ].join('');
                    }
                }
            ],
            onClickCell: function (field, value, row, $element) {

                if (field == "Operate") {
					return false;
				}

                var input = $($element).find("input");
                var select = $($element).find("select");
                if (input.length > 0 || select.length > 0)
                    return false;

                //当前列所在行的索引
                var index = $element.parent().attr("data-index");

				//审核、红冲后不能修改
				if ("@Model.AuditedStatus" == "True" || "@Model.ReversedStatus" == "True") {
					return false;
				}

				//验证无效或者单据已经审核则不允许修改编辑
				if (!formValidator() || $("#AuditedStatus").val() == "True") {
					return false;
				}

                if (field == "ProductName") {
                    //var html = '<input type="text" class="form-control input-sm" value="' + (typeof (value) == 'undefined' ? "" : value) + '" id="' + field + "_" + row.Id + '">';
                    var html = '<div class="input-group">' +
                        '<input type="text" class="form-control input-sm"  name="ProductName" value="' + (typeof (value) == 'undefined' ? "" : value) + '" id="' + field + "_" + row.Id + '">' +
                        '<span class="input-group-btn"><button class="btn btn-default btn-sm searchproduct" id="search_' + field + "_" + row.Id + '" data-index="' + index + '"><span class="glyphicon glyphicon-search"></span></button></span>' +
                        '</div>';

                    $($element).html(html);
                    var inputObj = $("#search_" + field + "_" + row.Id);
                    inputObj.focus();
                    inputObj.select();
                    inputObj.bind("focusout", function () {
						$("#ReturnReservationItems").bootstrapTable('updateRow', { index: index, row: { ProductName: value } });
                        $($element).html("" + value + "");
                    });
					//选择商品
					inputObj.bind("click", function () {
						//var wareHouseId = $("#WareHouseId").val();
						//注意销售订单，销售单，采购退货单，调拨单的出货仓库 ...涉及从仓库出库的逻辑，才判断此仓库库存是否有商品，wareHouseId=0不需要判断
						var wareHouseId = $("#WareHouseId").val();
                        var terminalId= $("#TerminalId").val();
                        var _this = this;
						$(this).productSelectShowModal($("#ModalProductWindows"), "/Product/AsyncSearchSelectPopup?wareHouseId=" + wareHouseId + "&&stockQtyMoreThan=true&includeProductDetail=0&terminalId=" + terminalId, { Index: $(this).attr("data-index") }, "选择商品", $("#ProductModalForm"),
                            function () {
                                var modal = $("#ModalProductWindows");
                                $('#btnSave_ModalProductWindows').bind('click', function () {
                                    $('#btnSave_ModalProductWindows').unbind();
                                    var allTableData = $('#products_datatable').bootstrapTable('getSelections');
                                    $.each(allTableData, function (i, row) {
                                        productOperateEvents(row, _this.dataset.index, _this);
                                    });
                                    modal.modal('hide');
                                });
                            });
                        return false;
					});
                }
                else if (["Price", "Quantity"].indexOf(field) >= 0)
                {
                    var html = '<input type="text" class="form-control input-sm" value="' + (typeof (value) == 'undefined' ? "0" : value) + '" id="' + field + "_" + row.Id + '">';

					if (field == "Price" || field == "Quantity") {

						if (field == "Price") {
							if (!row.IsAdjustPrice || row.IsAdjustPrice == true) {//允许变更价格
								$($element).html(html);
								var inputObj = $("#" + $(html).attr("id"));

								inputObj.focus();
								inputObj.select();

								inputObj.bind("focusout", function () {
									if ($(this).val() == "") {
										$(this).val(0);
									}
									row[field] = parseFloat($(this).val());
									$("#ReturnReservationItems").bootstrapTable('updateRow', { index: index, row: row });
									$($element).html("" + value + "");
								});

								inputObj.bind("change", function () {
									if (!isNaN($(this).val())) {
										if ($(this).val() == "") {
											$(this).val(0);
										}
										var oldQuantity = row.Quantity;
                                        row.Price = $(this).val();
                                        var newAmount = $(this).floatTimes(parseFloat($(this).val()), oldQuantity);
										row.Amount = newAmount;

										//成本金额
                                        row.CostAmount = $(this).floatTimes(oldQuantity, row.CostPrice);
										//含税价格
                                        row.ContainTaxPrice = $(this).floatTimes(parseFloat((1 + row.TaxRate / 100)), row.Price);
										//税额
                                        row.TaxPrice = $(this).floatTimes($(this).floatTimes(parseFloat(row.TaxRate / 100), row.Price), row.Quantity);
										//价税总计
                                        row.TaxPriceAmount = $(this).floatTimes(row.ContainTaxPrice, row.Quantity);
                                        if ('@Model.EnableTaxRate' !== 'True') {
                                            row.TaxPriceAmount = $(this).floatTimes(row.Price, row.Quantity);
                                        }


										//利润
										row.Profit = row.TaxPriceAmount - row.CostAmount;
										//成本利润率
										if (row.CostAmount == 0) {
											row.CostProfitRate = 100;
										} else {
											row.CostProfitRate = row.Profit / row.CostAmount * 100;
										}

                                        //格式化(先计算，再格式化，不然数据不准)
                                        row.Amount = parseFloat(row.Amount).toFixed(2);
                                        row.CostAmount = parseFloat(row.CostAmount).toFixed(2);
										row.ContainTaxPrice = parseFloat(row.ContainTaxPrice).toFixed(2);
										row.TaxPrice = parseFloat(row.TaxPrice).toFixed(2);
										row.TaxPriceAmount = parseFloat(row.TaxPriceAmount).toFixed(2);
                                        row.Profit = parseFloat(row.Profit).toFixed(2);
										row.CostProfitRate = parseFloat(row.CostProfitRate).toFixed(2);

									}
									else {
										$(this).val(0);
										$(this).showToastr("只能输入数字!");
									}
								});
							}
						}
						if (field == "Quantity") {

							$($element).html(html);
							var inputObj = $("#" + $(html).attr("id"));

							inputObj.focus();
							inputObj.select();

							inputObj.bind("focusout", function () {
								if ($(this).val() == "") {
									$(this).val(0);
								}
								//数量转整数
								row[field] = parseInt($(this).val());
								$("#ReturnReservationItems").bootstrapTable('updateRow', { index: index, row: row });
								$($element).html("" + value + "");
							});

							inputObj.bind("change", function () {
								if (!isNaN($(this).val())) {
									if ($(this).val() == "") {
										$(this).val(0);
									}
									var oldPrice = row.Price;
									//数量转整数
									row.Quantity = parseInt($(this).val());

                                    var newAmount = $(this).floatTimes(parseInt($(this).val()), oldPrice);
									row.Amount = newAmount;

									//成本金额
                                    row.CostAmount = $(this).floatTimes(parseInt($(this).val()), row.CostPrice);
									//含税价格
                                    row.ContainTaxPrice = $(this).floatTimes(parseFloat((1 + row.TaxRate / 100)), row.Price);
									//税额
                                    row.TaxPrice = $(this).floatTimes($(this).floatTimes(parseFloat(row.TaxRate / 100), row.Price), row.Quantity);
									//价税总计
                                     row.TaxPriceAmount = $(this).floatTimes(row.ContainTaxPrice, row.Quantity);
                                    if ('@Model.EnableTaxRate' !== 'True') {
                                        row.TaxPriceAmount = $(this).floatTimes(row.Price, row.Quantity);
                                    }

									//利润
									row.Profit = row.TaxPriceAmount - row.CostAmount;
									//成本利润率
									if (row.CostAmount == 0) {
										row.CostProfitRate = 100;
									} else {
										row.CostProfitRate = row.Profit / row.CostAmount * 100;
									}

                                    //格式化(先计算，再格式化，不然数据不准)
                                    row.Amount = parseFloat(row.Amount).toFixed(2);
                                    row.CostAmount = parseFloat(row.CostAmount).toFixed(2);
									row.ContainTaxPrice = parseFloat(row.ContainTaxPrice).toFixed(2);
									row.TaxPrice = parseFloat(row.TaxPrice).toFixed(2);
									row.TaxPriceAmount = parseFloat(row.TaxPriceAmount).toFixed(2);
                                    row.Profit = parseFloat(row.Profit).toFixed(2);
									row.CostProfitRate = parseFloat(row.CostProfitRate).toFixed(2);

								}
								else {
									$(this).val(0);
									$(this).showToastr("只能输入数字!");
								}
							});
						}

                    }
                    else {
                        $($element).html(html);
                        var inputObj = $("#" + $(html).attr("id"));
                        inputObj.focus();
                        inputObj.select();
                        inputObj.bind("focusout", function () {
                            row[field] = $(this).val();
                            $("#ReturnReservationItems").bootstrapTable('updateRow', { index: index, row: row });
                            $($element).html("" + value + "");
                        });
                    }



                }
                else if (field == "Remark") {
                    var html = '<input type="text" class="form-control input-sm" value="' + (typeof (value) == 'undefined' ? "" : value) + '" id="' + field + "_" + row.Id + '">';
                    $($element).html(html);
                    var inputObj = $("#" + $(html).attr("id"));
                    inputObj.focus();
                    inputObj.select();
                    inputObj.bind("focusout", function () {
                        $("#ReturnReservationItems").bootstrapTable('updateRow', { index: index, row: { Remark: $(this).val() } });
                        $($element).html("" + value + "");
                    });
                }
                else if (field == "UnitName") {
                    console.log("Units:" + row.Units);

                    if (row.Units == null) {
                        $(this).showToastr('请选择商品');
                        return;
                    }

                    console.log("UnitId:" + row.UnitId);

                    var html = '<select name="' + field + '" id="' + field + "_" + row.Id + '">';
                    //var keys = Object.keys(row.Units);
                    $.each(row.Units, function (key, unit) {
						if (unit > 0) {
							html += '<option value="' + unit + '"  ' + (row.UnitId == unit ? "selected" : "") + '>' + key + '</option>';
						}
                    });
                    html += '</select>';

                    $($element).html(html);

                    var inputObj = $("#" + $(html).attr("id"));
                    inputObj.focus();
                    inputObj.select();
                    inputObj.bind("focusout", function () {
                        console.log(row.UnitId + "=" + inputObj.val());
                        console.log(inputObj.find("option:selected").text());
                        $($element).html("" + inputObj.find("option:selected").text() + "");
                        //$("#ReturnReservationItems").bootstrapTable('updateRow', { index: index, row: { UnitName: inputObj.find("option:selected").text(),Units: row.Units } });
                        $("#ReturnReservationItems").bootstrapTable('updateRow', { index: index, row: { UnitName: inputObj.find("option:selected").text() } });
                    });

                    //单位选择
                    inputObj.bind("change", function () {
                        //alert("change");
                        //用户选择的价格体系
                        @*var defaultAmountId = "@Model.DefaultAmountId";*@
						var defaultAmountId = $("#DefaultAmountId").val();
                        //用户当前选择的单位
                        var unitId = $(this).val();
                        //价格
                        var price = 0;
                        //金额
						var amount = 0;

						//成本价
                        var costPrice = 0;
                        //成本金额
                        var costAmount = 0;
						var ck = Object.keys(row.CostPrices);
						var cv = Object.values(row.CostPrices);
						ck.forEach(function (a, b) {
							if (a == unitId) {
								costPrice = cv[b];
							}
						});

                        //判断用户当前选择的单位是小，中，大
                        var unitType = "SmallUnitId";
                        if (unitId == row.SmallUnitId) {
                            unitType = "SmallUnitId";
                        }
                        if (unitId == row.StrokeUnitId) {
                            unitType = "StrokeUnitId";
                        }
                        if (unitId == row.BigUnitId) {
                            unitType = "BigUnitId";
                        }

                        //先个给一个默认价格
                        row.Prices.forEach(function (a, b) {
                            if (a.UnitId == unitId) {
								//price = a.ProductPrice.TradePrice;
								costPrice = a.ProductPrice.CostPrice;
                            }
                        });

                        //如果此商品有价格体系
                        row.ProductTierPrices.forEach(function (a, b) {
                            var planIdTypeId = a.PricesPlanId + "_" + a.PriceTypeId;
                            if (defaultAmountId == planIdTypeId) {
                                if (unitType == "SmallUnitId") {
                                    price = a.SmallUnitPrice;
                                }
                                if (unitType == "StrokeUnitId") {
                                    price = a.StrokeUnitPrice;
                                }
                                if (unitType == "BigUnitId") {
                                    price = a.BigUnitPrice;
                                }
                            }
                        });

						amount = parseFloat(parseFloat((row.Quantity == undefined || row.Quantity == "") ? "0" : row.Quantity) * parseFloat(price)).toFixed(2);
						costAmount = parseFloat(parseFloat((row.Quantity == undefined || row.Quantity == "") ? "0" : row.Quantity) * parseFloat(costPrice)).toFixed(2);

						$("#ReturnReservationItems").bootstrapTable('updateRow', { index: index, row: { UnitId: unitId, UnitName: inputObj.find("option:selected").text(), Units: row.Units, Price: price, Amount: amount, CostPrice: costPrice, CostAmount: costAmount } });

                    });

                }
                else if (field == "ManufactureDete") {
                    if (row.IsManufactureDete == true) {
                        var html = '<select class="form-control input-sm" name="' + field + '" id="' + field + "_" + row.Id + '">';
                        if (row.ProductTimes != null) {
                            $.each(row.ProductTimes, function (key, date) {
                                if (date > 0) {
                                    html += '<option value="' + date + '"  ' + (row.ManufactureDete == date ? "selected" : "") + '>' + key + '</option>';
                                }
                            });
                        }

                        html += '</select>';

                        $($element).html(html);

                        var inputObj = $("#" + $(html).attr("id"));
                        inputObj.focus();
                        inputObj.select();
                        inputObj.bind("focusout", function () {
                            console.log(row.ManufactureDete + "=" + inputObj.val());
                            console.log(inputObj.find("option:selected").text());
                            $($element).html("" + inputObj.find("option:selected").text() + "");
                            $("#ReturnReservationItems").bootstrapTable('updateRow', { index: index, row: { ManufactureDete: inputObj.find("option:selected").text() } });
                        });
                    }
                }
                else if (field == "TaxRate") {
					html = '<input type="text" class="form-control input-sm" value="' + (typeof (value) == 'undefined' ? "0" : value) + '" id="' + field + "_" + row.Id + '">';
					$($element).html(html);
					var inputObj = $("#" + $(html).attr("id"));

					inputObj.focus();
					inputObj.select();

					inputObj.bind("focusout", function () {
						if ($(this).val() == "") {
							$(this).val(0);
						}
						if ($(this).val()>100) {
							$(this).showToastr("税率不能大于100!");
							$(this).val(0);
						}
						row[field] = parseFloat($(this).val());
						$("#ReturnReservationItems").bootstrapTable('updateRow', { index: index, row: row });
						$($element).html("" + value + "");
					});

					inputObj.bind("change", function () {
						if (!isNaN($(this).val())) {
							if ($(this).val() == "") {
								$(this).val(0);
							}
							if ($(this).val() > 100) {
								$(this).showToastr("税率不能大于100!");
								$(this).val(0);
							}
                            //税率
							row.TaxRate = parseFloat($(this).val()).toFixed(2);
							//含税价格
                            row.ContainTaxPrice = $(this).floatTimes(parseFloat((1 + $(this).val() / 100)), row.Price);
							//税额
                            row.TaxPrice = $(this).floatTimes($(this).floatTimes(parseFloat($(this).val() / 100), row.Price), row.Quantity);
							//价税总计
                            row.TaxPriceAmount = $(this).floatTimes(row.ContainTaxPrice, row.Quantity);
                            if ('@Model.EnableTaxRate' !== 'True') {
                                row.TaxPriceAmount = $(this).floatTimes(row.Price, row.Quantity);
                            }

							//利润
							row.Profit = row.TaxPriceAmount - row.CostAmount;
							//成本利润率
							if (row.CostAmount == 0) {
								row.CostProfitRate = 100;
							} else {
								row.CostProfitRate = row.Profit / row.CostAmount * 100;
							}

                            //格式化(先计算，再格式化，不然数据不准)
                            row.Amount = parseFloat(row.Amount).toFixed(2);
                            row.CostAmount = parseFloat(row.CostAmount).toFixed(2);
							row.ContainTaxPrice = parseFloat(row.ContainTaxPrice).toFixed(2);
							row.TaxPrice = parseFloat(row.TaxPrice).toFixed(2);
							row.TaxPriceAmount = parseFloat(row.TaxPriceAmount).toFixed(2);
                            row.Profit = parseFloat(row.Profit).toFixed(2);
							row.CostProfitRate = parseFloat(row.CostProfitRate).toFixed(2);

						}
						else {
							$(this).val(0);
							$(this).showToastr("只能输入数字!");
						}
					});
				}

                $.each($('#ReturnReservationItems').bootstrapTable('getData'), function (i, row) {
                    //console.log(row);
                });
            }
        });

        //优惠
		$("#PreferentialAmount").bind("change", function () {

			if (isNaN($(this).val()) || $(this).val() == "" || parseFloat($(this).val()) < 0) {
				$(this).val("0.00")
			}
            $("#PreferentialAmount").focus();
            var sumAmount = $("#SumAmount").val();
            var oweCash = (parseFloat(sumAmount) - parseFloat($(this).val())).toFixed(2);
            $("#PreferentialEndAmount").val(oweCash);
            //欠款金额
            //$("#OweCash").val(parseFloat(oweCash - SumAlreadyAmount()).toFixed(model.AccuracyRounding));
            //剩余欠款金额
            var thisOwnCash = parseFloat(oweCash - SumAlreadyAmount()).toFixed(2);
            if (thisOwnCash < 0) {
                $(this).val("0.00");
                $("#PreferentialEndAmount").val((parseFloat(sumAmount)).toFixed(2));
                $("#OweCash").val(parseFloat(parseFloat(sumAmount) - SumAlreadyAmount()).toFixed(2));
            } else {
                $("#OweCash").val(thisOwnCash);
            }
        });
		//优惠金额选择
		$("#PreferentialAmount").focus(function () {
			$("#PreferentialAmount").select();
		});

		//科目选择
		$(document).on('click', "#ReturnReservationItems_Partial_Form input[name='CollectionAmount']", function () {
			$(this).select();
		});
        //科目
		$(document).on('change', "#ReturnReservationItems_Partial_Form input[name='CollectionAmount']", function () {
            $(this).focus();

            if (isNaN($(this).val())) {
                $(this).showToastr("只能输入数字!");
                $(this).val('0.0');
                return false;
            }

            if (parseInt($(this).val()) < 0 && $(this).attr("data-codetype") != 24) {
                $(this).showToastr("只能输入正数!");
                $(this).val('0.0');
                return false;
            }
            else {
                if ($(this).attr("data-codetype") == 24) {
                    if (model.AllowAdvancePaymentsNegative == false && parseInt($(this).val()) < 0) {
                        $(this).showToastr("只能输入正数!");
                        $(this).val('0.0');
                        return false;
                    }
                }
            }

            var preferentialEndAmount = $("#PreferentialEndAmount").val();

            //欠款金额=优惠后金额-已收会计科目总金额
            //var oweCash = (parseFloat(preferentialEndAmount) - SumAlreadyAmount()).toFixed(model.AccuracyRounding);
            //$("#OweCash").val(oweCash);
            var thisOwnCash = (parseFloat(preferentialEndAmount) - SumAlreadyAmount()).toFixed(2);
            //剩余欠款金额
            if (thisOwnCash < 0) {
                $(this).val("0.00");
                $("#OweCash").val(parseFloat(parseFloat(preferentialEndAmount) - SumAlreadyAmount()).toFixed(2));
            } else {
                $("#OweCash").val(thisOwnCash);
            }
		});

        //保存服务器
        var submitRemoteServer = function (items, showMessage, doAudit, callback,loadingButton)
        {
			if (!formValidator()) {
	            if(loadingButton != undefined){
				   loadingButton.stop();
			    }
				return false;
            };
            var reg=/^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 ，判断正整数用/^[1-9]+[0-9]*]*$/

            //获取表格的所有内容行
            var allTableData = $('#ReturnReservationItems').bootstrapTable('getData');
            var accounts = $("#ReturnReservationItems_Partial_Form").find("input[name='CollectionAmount']");
            var flag = 0;
            var numFlag = 0;
            var accFlag = 0;
            var errMsg = "";
            $.each(allTableData, function (i, row) {
                if (Object.keys(row).length > 1) {
                    var manDate = $("#selDate_" + i).val();
                    if (row.ProductId == "" || row.Quantity == "" || (manDate == "" && row.IsManufactureDete == true))
                        flag++;
                    else if (!reg.test(row.Quantity))
                        numFlag++;
                    else if (!reg.test(row.Price))
                        numFlag++;
                    if (row.ProductId != "" && row.Quantity == "") {
                        errMsg += "商品：" + row.ProductName + " 数量为0.";
                    }
                    if (row.ProductId != "" && row.Price == 0 && row.Remark == "") {
                        errMsg += "商品：" + row.ProductName + " ,0元开单，必须选择备注.";
                    }
                }
            });

            //商品验证
            if (errMsg != "") {
                if (loadingButton != undefined) {
                    loadingButton.stop();
                }
                $(this).showToastr(errMsg);
                return false;
            }

            if ($("#WareHouseId").val() == 0 || $("#WareHouseId").val() == "") {
                if (loadingButton != undefined) {
                    loadingButton.stop();
                }
                $(this).showToastr("请选择仓库!");
                return false;
            }

            if ($("#BusinessUserId").val() == 0 || $("#BusinessUserId").val() == "") {
                if (loadingButton != undefined) {
                    loadingButton.stop();
                }
                $(this).showToastr("请选择业务员!");
                return false;
            }

            $.each(accounts, function (i, input) {
                if (isNaN($(input).val()))
                    accFlag++;
            });

            if (flag == allTableData.length) {
	            if(loadingButton != undefined){
				   loadingButton.stop();
			    }
                $(this).showToastr("请先填写单据明细！");
                return false;
            }
            else if (numFlag > 0) {
	            if(loadingButton != undefined){
				   loadingButton.stop();
			    }
                $(this).showToastr("数量只允许输入数字！");
                return false;
            }
            else if (accFlag > 0) {
	            if(loadingButton != undefined){
				   loadingButton.stop();
			    }
                $(this).showToastr("收款账户信息中数据格式不正确!");
                return false;
            }


            var serializeData = [];
            var accountingOption = { AccountingOptionId: 0, CollectionAmount: 0 };
            var accountings = [];
            $.each(allTableData, function (i, row) {
                var manDate = $("#selDate_" + i).val();
                var tmpObj = {
                    "Id": typeof (row.Id) == 'undefined' ? "0" : row.Id,
                    "ProductId": typeof (row.ProductId) == 'undefined' ? "0" : row.ProductId,
                    "UnitId": typeof (row.UnitId) == 'undefined' ? "0" : row.UnitId,
                    "Quantity": typeof (row.Quantity) == 'undefined' ? "0" : row.Quantity,
                    "Price": typeof (row.Price) == 'undefined' ? "0" : row.Price,
					"Amount": typeof (row.Amount) == 'undefined' ? "0" : row.Amount,
					"CostPrice": typeof (row.Price) == 'undefined' ? "0" : row.CostPrice,
					"CostAmount": typeof (row.Amount) == 'undefined' ? "0" : row.CostAmount,
                    "StockQty": typeof (row.StockQty) == 'undefined' ? "0" : row.StockQty,
                    "RemainderQty": typeof (row.RemainderQty) == 'undefined' ? "0" : row.RemainderQty,
                    "Remark": typeof (row.Remark) == 'undefined' ? "" : row.Remark,
					"ManufactureDete": typeof (row.ManufactureDete) == 'undefined' ? "" : row.ManufactureDete,
                    "TaxRate": typeof (row.TaxRate) == 'undefined' ? "0" : row.TaxRate,
				    "ContainTaxPrice":typeof (row.ContainTaxPrice) == 'undefined' ? "0" : row.ContainTaxPrice
                };
                serializeData.push(tmpObj);
            });

            //获取收款账户
            $.each(accounts, function (i, input) {
                var option = $(input).attr("data-account");
                var amount = $(input).val();
                accountings.push({ AccountingOptionId: option, CollectionAmount: $(input).val() });
            });

            //保存的数据
            var postData = {
                //客户
				TerminalId: $("#TerminalId").val(),
                //业务员
                BusinessUserId: $("#BusinessUserId").val(),
                //仓库
                WareHouseId: $("#WareHouseId").val(),
                //送货员
                DeliveryUserId: $("#DeliveryUserId").val(),
                //付款方式
                PayTypeId: $("#PayTypeId").val(),
                //交易日期
                TransactionDate: $("input[name='TransactionDate']").val(),
                //按最小单位销售
                IsMinUnitSale: $("#IsMinUnitSale").val(),
                //备注
                Remark: $("#Remark").val(),
                //价格体系
                DefaultAmountId: $("#DefaultAmountId").val(),
                //优惠金额
                PreferentialAmount: $("#PreferentialAmount").val(),
                //优惠后金额
                PreferentialEndAmount: $("#PreferentialEndAmount").val(),
                //待支付金额
                OweCash: $("#OweCash").val(),
                //商品项目
                Items: serializeData,
                //收款账户
                Accounting: accountings,
                //单号
                BillNumber: $("#BillNumber").val(),
            };


            //保存服务器
            $(this).remoteSubmit("post", "/ReturnReservationBill/CreateOrUpdate?billId=@(Model.Id)&doAudit=" + doAudit, postData, items, callback, showMessage,loadingButton);
        }


        //保存单据项目
        $("#FormSubmit").click(function () {
            var doAudit = true;
	         var loadingButton = Ladda.create(this);
	         loadingButton.start();

            submitRemoteServer(null, null, doAudit, function (data) {
                if (data.Success) {
                     window.location.href = "/ReturnReservationBill/List";
                }
            }, loadingButton);
        });

        //保存并继续
        $("#FormSubmitContinue").click(function () {
            var doAudit = false;
	         //防止重复保存
	         var loadingButton = Ladda.create(this);
	         loadingButton.start();
            if ("@Model.Id" == "0") {
                submitRemoteServer(null, null, doAudit, function () { window.location.href = "/ReturnReservationBill/Create"; },loadingButton);
            } else {
                submitRemoteServer($("#ReturnReservationItems"), null, doAudit, function () { window.location.href = "/ReturnReservationBill/Edit/" + "@Model.Id"; },loadingButton);
			}
        });
        //


        //会计科目选择
        $(document).on('click', "#Accounting_AsyncSearchSelectPopup", function () {
            //var actionUrl = "/Accounting/AsyncSearchSelectPopup?type=1&accountCodeTypeIds="+"1,2,4,75";
            var billTypeId = $("#BillTypeEnumId").val();
            var actionUrl = "/Accounting/AsyncSearchSelectPopup?billTypeId=" + billTypeId;
            $(this).accountingSearchSelectPopup($("#AccountingModalWindow"), actionUrl, null, "选择科目", $("#AccountingForm"), $("#CollectionAccount"), $("#CollectionAccountBox"));
        });


        /*
         * ======================================================
         * mschen 2018-12-5 11:24:43 end
         * ======================================================
         */
    });

</script>